package org.lql.algo.codecrush.week010;

import org.lql.algo.common.TreeNode;

/**
 * @author: liangqinglong
 * @date: 2025-08-30 15:11
 * @description: LCR 193. 二叉搜索树的最近公共祖先 <a href="https://leetcode.cn/problems/er-cha-sou-suo-shu-de-zui-jin-gong-gong-zu-xian-lcof/description/">...</a>
 **/
public class LowestCommonAncestorEasy {

	public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
		TreeNode ancestor = root;
		while (true) {
			if (p.val < ancestor.val && q.val < ancestor.val) {
				ancestor = ancestor.left;
			} else if (p.val > ancestor.val && q.val > ancestor.val) {
				ancestor = ancestor.right;
			} else {
				break;
			}
		}
		return ancestor;
	}

	public static void main(String[] args) {
		LowestCommonAncestorEasy lowestCommonAncestorEasy = new LowestCommonAncestorEasy();
		TreeNode root = new TreeNode(6);
		TreeNode p = new TreeNode(2);
		TreeNode q = new TreeNode(8);
		TreeNode ans = lowestCommonAncestorEasy.lowestCommonAncestor(root, p, q);
		System.out.println(ans.val);
	}

}
